package org.easyexcel.Test;

import lombok.AllArgsConstructor;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import static java.util.concurrent.TimeUnit.SECONDS;

public class LeGuanLock {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            Transformer ts = new UnsafeTransformer(10000);
            Transformer.demo(ts);
            System.out.println("===========================");
            Transformer ts1 = new SafeTransformerCas(10000);
            Transformer.demo(ts1);
            System.out.println("<<<<<<<<===========================>>>>>>>>");

        }

    }
}

interface Transformer {
    void transform(Integer pay);

    Integer get();

    static void demo(Transformer ts) {
        ArrayList<Thread> list = new ArrayList<>();
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 1000; i++) {
            list.add(new Thread(() -> {
                ts.transform(10);
            }));
        }

        list.forEach(Thread::start);
        list.forEach(t -> {
            try {
                t.join();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        long endTime = System.currentTimeMillis();
        long duration = endTime - startTime; // 计算执行时间（毫秒）
        System.out.println(ts.get());
        System.out.println("执行时间：" + duration + "毫秒");
    }
}

@AllArgsConstructor
class UnsafeTransformer implements Transformer {
    private int cost;

    public void transform(Integer pay) {
        this.cost -= pay;
        try {
            Thread.sleep(1); // 引入延迟，模拟业务处理时间
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    @Override
    public Integer get() {
        return this.cost;
    }
}

class SafeTransformerCas implements Transformer {
    private AtomicInteger cost;

    public SafeTransformerCas(int i) {
        this.cost = new AtomicInteger(i);
    }

    public void transform(Integer pay) {
//        while (true) {
//            int oldValue = cost.get();
//            int newValue = oldValue - pay;
//            if (cost.compareAndSet(oldValue, newValue)) {
//                break;
//            }
//        }
        cost.addAndGet(-pay);
    }

    @Override
    public Integer get() {
        return cost.get();
    }
}


/**
 * @author DPF
 */
class DataSafeTransformer {

    public static void main(String[] args) {
        List<String> m = m("2023-07-01 00:00:00");
        m.forEach(System.out::println);
    }

    private static List<String> m(CharSequence text) {
        DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(100);
        ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 11, 100, TimeUnit.SECONDS, queue);
        ArrayList<String> list = new ArrayList<>();
        // 提交10个任务到线程池
        for (int i = 0; i < 10; i++) {
            executor.execute(() -> {
                // 解析并格式化日期字符串
                LocalDateTime dateTime = LocalDateTime.parse(text, inputFormatter);
                String formattedDate = dateTime.format(outputFormatter);
                list.add(formattedDate);
            });
        }
        // 关闭线程池以确保所有任务完成后再退出程序
        executor.shutdown();
        try {
            // 等待所有任务完成
            if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
                executor.shutdownNow();
            }
        } catch (InterruptedException e) {
            executor.shutdownNow();
        }
        return list;
    }
}

